﻿Imports System.Globalization
Imports System.ComponentModel
Imports System.Threading

Public Class FormTranslator

    Public Shared Sub ChangeFormLanguage(ByRef myform As Form, ByVal lang As String)
        Thread.CurrentThread.CurrentUICulture = New CultureInfo(lang)
        If Not myform.MainMenuStrip Is Nothing Then
            For Each m As ToolStripMenuItem In myform.MainMenuStrip.Items
                ChangeLanguageOnMenu(m, New CultureInfo(lang), myform)
            Next
        End If

        For Each c As Control In myform.Controls
            ChangeLanguageOnControls(c, New CultureInfo(lang), myform)
        Next c
    End Sub

    Private Shared Sub ChangeLanguageOnControls(ByVal c As Control, ByVal ci As CultureInfo, ByVal myform As Form)

        Dim resources As ComponentResourceManager = New ComponentResourceManager(myform.GetType())
        resources.ApplyResources(c, c.Name, ci)
        For Each cc As Control In c.Controls
            ChangeLanguageOnControls(cc, ci, myform)
        Next
    End Sub

    Private Shared Sub ChangeLanguageOnMenu(ByVal m As ToolStripMenuItem, ByVal ci As CultureInfo, ByVal myform As Form)

        Dim resources As ComponentResourceManager = New ComponentResourceManager(myform.GetType())
        resources.ApplyResources(m, m.Name, ci)
        For Each dd As Object In m.DropDownItems
            If dd.GetType() = GetType(ToolStripMenuItem) Then 'to avoid separator problems
                ChangeLanguageOnMenu(dd, ci, myform)
            End If

        Next
    End Sub

    Public Shared Sub ResetToDefault()
        Thread.CurrentThread.CurrentUICulture = CultureInfo.InstalledUICulture
        For Each Form In Application.OpenForms
            ChangeFormLanguage(Form, Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName)
        Next
    End Sub

End Class
